package com.imut.lagain.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;

import java.io.File;

/**
 * 文件上传配置类
 */
@Configuration
public class FileUploadConfig {
    private static final Logger log = LoggerFactory.getLogger(FileUploadConfig.class);

    
    @Value("${file.upload.path}")
    private String uploadPath;
    
    @Value("${file.upload.max-file-size}")
    private String maxFileSize;
    
    @Value("${file.upload.max-request-size}")
    private String maxRequestSize;
    
    /**
     * 配置文件上传解析器
     */
    @Bean
    public MultipartResolver multipartResolver() {
        return new StandardServletMultipartResolver();
    }
    
    /**
     * 初始化上传目录
     */
    @Bean
    public String initUploadDirectory() {
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            boolean created = uploadDir.mkdirs();
            if (created) {
                System.out.println("Upload directory created: " + uploadPath);
            } else {
                System.err.println("Failed to create upload directory: " + uploadPath);
            }
        }
        createSubDirectories(uploadDir);
        
        return uploadPath;
    }
    
    /**
     * 创建子目录
     */
    private void createSubDirectories(File uploadDir) {
        String[] subDirs = {"images", "audio", "video", "documents", "temp"};
        
        for (String subDir : subDirs) {
            File dir = new File(uploadDir, subDir);
            if (!dir.exists()) {
                boolean created = dir.mkdirs();
                if (created) {
                    System.out.println("Sub directory created: " + dir.getAbsolutePath());
                }
            }
        }
    }
    
    /**
     * 获取上传路径
     */
    public String getUploadPath() {
        return uploadPath;
    }
    
    /**
     * 获取最大文件大小
     */
    public String getMaxFileSize() {
        return maxFileSize;
    }
    
    /**
     * 获取最大请求大小
     */
    public String getMaxRequestSize() {
        return maxRequestSize;
    }
}
